/**
 * Created by zsgjs on 2017/2/13.
 */

import React, { Component } from 'react';

import model from '../classes/Model';

import {
    StyleSheet,
    Text,
    View,
    Image,
    ListView,
    TouchableOpacity,
    Animated,
    RefreshControl,
    ScrollView
} from 'react-native'

var tableSoruce;
var TimerMixin = require('react-timer-mixin');

var Charts = React.createClass({
     mixins : [TimerMixin],

    getInitialState(){
        var getSectionData = (dataBolb, sectionID) => {
            return dataBolb[sectionID]
        };

        var getRowData = (dataBolb, sectionID, rowID) => {
            return dataBolb[sectionID + ':' + rowID];
        };

        return {
            listData: new ListView.DataSource({
                getSectionData: getSectionData,
                getRowData: getRowData,
                rowHasChanged: (row1, row2)=>row1 !== row2,
                sectionHeaderHasChanged: (s1, s2) => s1 !== s2
            }),

            followeds: [],

            isRefreshing: false
        }
    },

    componentDidMount() {
        this.loadListViewData();
    },

    render() {
        return (
            <View style={chartsStyle.container}>
                <View style={chartsStyle.navStyle}>
                    <View style={chartsStyle.navContent}>
                        <TouchableOpacity onPress={this.back}>
                            <Text style={chartsStyle.leftItem}>{'<'}</Text>
                        </TouchableOpacity>
                            <Text style={chartsStyle.navTitle}>排行榜</Text>

                    </View>
                </View>

                <Segement
                    ref="Segement"
                    handleSelecteItem={this.handlerSelect}
                    titles={['掌金达人', '掌金名人']}
                ></Segement>
                <ScrollView
                    ref='scroll'
                    style={chartsStyle.scrollStyle}
                    bounces={false}
                    horizontal={true}
                    pagingEnabled={true}
                    onScroll={this.onScrolling}
                    scrollEventThrottle={20}
                    showsHorizontalScrollIndicator={false}
                >
                    {this._renderListView()}

                </ScrollView>


            </View>
        )
    },

    _renderListView() {
        var lists = [];
        for (var i = 0; i < 2; i++) {
            lists.push(
                <ListView
                    key={i}
                    refreshControl={
                          <RefreshControl
                            refreshing={this.state.isRefreshing}
                            onRefresh={this._onRefresh}
                            tintColor="#ff0000"
                            title="刷新中……"
                            titleColor="#00ff00"
                             colors={['#ff0000', '#00ff00', '#0000ff']}
                            progressBackgroundColor="#ffff00"
                            progressViewOffset={44}
                          />
                    }
                    dataSource={this.state.listData}
                    renderRow={this.renderRows}
                    renderSectionHeader={this.renderSectionHeader}
                    showsVerticalScrollIndicator={false}
                >
                </ListView>
            )
        }
        return lists;
    },

    _onRefresh(){
        this.setState({
            isRefreshing:true
        });

        setTimeout(()=>{
            this.setState({
                isRefreshing:false
            });
        }, 1000)
    },

    renderRows(data, secID, rowID) {

        var focusStyle, focusText;
        var followed = this.state.followeds[rowID];

        if (followed) {
            focusStyle= {color: '#ccc', fontSize: 12};
            focusText = '取消关注'
        } else  {
            focusStyle= {color: 'orange', fontSize: 12};
            focusText = '+ 关注'
        }
        return (
            <View style={chartsStyle.rowStyle}>
                <View style={chartsStyle.rowContent}>
                    <View style={chartsStyle.leftContent}>
                        <Text style={chartsStyle.numberText}>{rowID}</Text>
                        <Image style={chartsStyle.advator}></Image>
                        <View style={chartsStyle.userInfoContainer}>
                            <Text style={chartsStyle.userName}>猫头鹰</Text>
                            <Text style={chartsStyle.fansCount}>粉丝数量：1234</Text>
                        </View>
                    </View>

                    <View style={chartsStyle.rightButton}>
                        <TouchableOpacity
                            onPress={this.follow.bind(this, rowID)}
                            activeOpacity={0}
                        >
                            <Text style={focusStyle}>{focusText}</Text>
                        </TouchableOpacity>

                    </View>
                </View>

                <View style={chartsStyle.seperatorLine}></View>
            </View>
        )
    },

    follow(index) {
        var follows = this.state.followeds;
        follows[index] = !follows[index];
        console.log(follows);
        this.setState({
            listData: tableSoruce,
            followeds: follows,
        })
    },

    renderSectionHeader(data) {
        return (
            <View style={chartsStyle.headerContent}>
                <Text style={chartsStyle.leftTextStyle}>{data}</Text>
                <View style={chartsStyle.rightItemsContent}>
                    <Text style={chartsStyle.paihang}>排行</Text>
                    <Text style={chartsStyle.rightTextStyle}>领先50%的用户</Text>
                </View>

            </View>
        )
    },


    loadListViewData() {

        var data = [
            {
                title:'共有0位粉丝',
                persons:['掌金达人', '掌金名人', '掌金达人', '掌金名人', '掌金达人', '掌金名人','掌金达人', '掌金名人', '掌金名人', '掌金达人', '掌金名人', '掌金达人', '掌金名人','掌金达人', '掌金名人', '掌金名人', '掌金达人', '掌金名人', '掌金达人', '掌金名人','掌金达人', '掌金名人']
            }];
        var followsArr = [];

        for (var i = 0; i < data[0].persons.length; i++) {
            followsArr.push(false);
        }


        var dataBolb = {};
        var sectionIDS = [];
        var rowIDs = [];
        var personList = []

        for (var i = 0; i < data.length; i++) {
            sectionIDS.push(i);
            dataBolb[i] = data[i].title;
            personList = data[i].persons;
            rowIDs[i] = [];

            for (var j = 0; j < personList.length; j++) {
                rowIDs[i].push(j);
                dataBolb[i + ':' + j] = personList[i];
            }
        }

        tableSoruce = this.state.listData.cloneWithRowsAndSections(dataBolb, sectionIDS, rowIDs)

        this.setState({
            listData: tableSoruce,
            followeds: followsArr
        })



    },

    back(){
        this.props.navigator.pop();
    },

    onScrolling(e) {
        var offset_x = (e.nativeEvent.contentOffset.x);
        var index;
        if (offset_x > model.screen_w * 0.5) {
            index = 1;
        } else  {
            index = 0;
        }
        var itemOffsetX = offset_x * (model.screen_w  * 0.5 ) / model.screen_w + (model.screen_w * 0.5 - itemWidth) * 0.5;
        this.refs['Segement'].itemScrollTo(itemOffsetX, index)
    },

    handlerSelect(index) {
        this.refs['scroll'].scrollTo({y: 0, x:model.screen_w * index, true});
    }
});


const itemWidth = 64;
const Segement = React.createClass({
    getDefaultProps(){
        return {
            titles:[],
        }
    },

    getInitialState(){
        return {
            selectTag:0,
            leftValue: (model.screen_w * 0.5 - itemWidth) * 0.5,
            transformValue: new Animated.Value(0)
        }
    },

    render() {
        var animateStyle = {transform:[{
            translateX: this.state.transformValue.interpolate({
                inputRange: [0, 1],
                outputRange: [0, (model.screen_w * 0.5)]
            }),
        }]};

        var itemLeftStyle = {left: this.state.leftValue};

        return (
            <View style={segementStyle.SegementContent}>
                {this.renderSegement()}
                <Animated.View style={[segementStyle.slideItem, itemLeftStyle, animateStyle]}></Animated.View>
            </View>
        )
    },

    renderSegement() {
        var items = [];
        var itemTitleStyle;

        for (var i = 0; i < this.props.titles.length; i++) {
            if (this.state.selectTag == i) itemTitleStyle = {color:'red', fontWeight:'bold'};
            else itemTitleStyle = {color:'gray'};
            items.push(
                <View key={i} style={segementStyle.segement}>
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={this.pressItem.bind(this,i)}
                    >
                        <Text style={[segementStyle.itemTitle, itemTitleStyle]}>{this.props.titles[i]}</Text>
                    </TouchableOpacity>
                </View>
            )
        }
        return items;
    },

    pressItem(index) {
        if (this.state.selectTag == index) return;
        this.props.handleSelecteItem(index);
    },

    itemScrollTo(offset, index) {

        this.setState({
            leftValue: offset,
            selectTag: index
        })
    }

});

const segementStyle = StyleSheet.create({
    SegementContent: {
        height: 35,
        width: model.screen_w,
        backgroundColor:'white',
        flexDirection:'row',
    },

    segement: {
        height: 35,
        width: model.screen_w * 0.5,
        alignItems:'center',
        justifyContent:'center'
    },

    itemTitle:{
        width: itemWidth,
        fontSize:15,
        textAlign:'center'
    },

    slideItem: {
        position:'absolute',
        height: 2,
        backgroundColor:'red',
        width: itemWidth,
        bottom: 0
    }
});

const chartsStyle = StyleSheet.create({
    container:{
        flex:1,
    },

    navStyle: {
        height: 64,
        width: model.screen_w,
        backgroundColor: 'red'
    },

    navContent: {
        height: 44,
        marginTop: 20,
        flexDirection: 'row'
    },

    leftItem: {
        color: 'white',
        fontSize: 18,
        fontWeight: 'bold',
        height: 44,
        marginLeft: 10,
        lineHeight: 44,
    },

    navTitle: {
        position: 'absolute',
        color: 'white',
        fontSize: 18,
        fontWeight: 'bold',
        height: 44,
        lineHeight: 44,
        width: 100,
        left: (model.screen_w - 100) * 0.5,
        textAlign: 'center'
    },

    scrollStyle: {
        width: model.screen_w,
        height: model.screen_h - 64 - 35,
    },

    headerContent: {
        backgroundColor: '#ddd',
        height: 20,
        flexDirection: 'row',
        justifyContent:'space-between'
    },

    leftTextStyle: {
        fontSize: 12,
        height: 20,
        lineHeight: 20,
        marginLeft: 10,
    },

    rightItemsContent: {
        flexDirection:'row',
        height: 20,
        alignItems:'center'
    },

    paihang: {
        fontSize: 12,
        height: 20,
        lineHeight: 20,
        color:'#aaa',
    },

    rightTextStyle: {
        fontSize: 12,
        height: 20,
        lineHeight: 20,
        color:'orange',
        marginRight: 10,
        marginLeft: 10
    },

    rowStyle: {
        height: 44,
    },

    rowContent: {
        height: 43,
        width: model.screen_w,
        flexDirection:'row',
        alignItems:"center",
        justifyContent:'space-between'
    },

    leftContent: {
        height: 43,
        flexDirection:'row',
        alignItems:"center",
    },

    numberText: {
        color:'green',
        fontSize: 14,
        height: 43,
        lineHeight: 43,
        marginLeft: 10,
        width: 40,
        textAlign:'center'
    },

    advator: {
        width: 30,
        height: 30,
        borderRadius: 15,
        backgroundColor:  'orange',
    },

    userInfoContainer: {
        marginLeft:10,
        height: 32,
        justifyContent:'space-between'
    },

    userName: {
        color: 'red',
        fontSize: 13,
        fontWeight: 'bold'
    },

    fansCount: {
        color: '#aaa',
        fontSize: 12,
    },

    seperatorLine: {
        height: 1,
        width: model.screen_w,
        backgroundColor: '#eee'
    },


    rightButton: {
        width: 60,
        height: 20,
        borderRadius: 5,
        borderColor: '#ddd',
        borderWidth: 1,
        alignItems:'center',
        justifyContent:'center',
        marginRight: 10
    }
});

module.exports = Charts;
